package drds.plus.executor.function.scalar.string;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

/**
 * <pre>
 * INSTR(str,substr)
 *  Returns the position of the firstInNewCursor occurrence of substring substr in string str. This is the same setAliasAndSetNeedBuild the two-argument form of LOCATE(), except that the order of the argList is reversed.
 *
 * mysql> SELECT INSTR('foobarbar', 'bar');
 *         -> 4
 * mysql> SELECT INSTR('xbar', 'foobar');
 *         -> 0
 * </pre>
 *
 * @author mengshi.sunmengshi 2014年4月11日 下午4:56:34
 * @since 5.1.0
 */
public class Instr extends ScalarFunction {

    public Type getReturnType() {
        return Type.IntegerType;
    }

    public String[] getFunctionNames() {
        return new String[]{"INSTR"};
    }

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }

        String str = Type.StringType.convert(args[0]);
        String subStr = Type.StringType.convert(args[1]);

        return str.indexOf(subStr) + 1;

    }

}
